Numbers


In [1]:
"""
Multi-line
comment
"""
a = 7           # integer
b = 2.9         # float
c = 10 + 2j     # complex
d = a + b       # sum
e = a // b      # integer division
f = a % 5       # remainder of the division
g = a ** 3      # power
print a, b, c, d, e, f, g


7 2.9 (10+2j) 9.9 2.0 2 343

In [2]:
a = round(1.5)        # floor
b = abs(-10)          # absolute value
c = min(1, 2, 3)      # minimum value
print a, b, c


2.0 10 1

Strings


In [3]:
a = 'some string'
b = "another one"

c = int('10')                    # convert to integer
d = len('string')                # length of string

d = 'We ' + 'can ' + 'concatenate' + '\n'   # concatenate
e = 'We %s format %d' % ('can', 10)       # format string

print a, b, c, d, e


some string another one 10 We can concatenate
We can format 10

Boolean


In [4]:
a = True
b = 2 > 1
c = 1 == 2
d = 'o' in 'abcd'
print a, b, c, d


True True False False

Lists


In [5]:
a = [1, 2, 3.5, 4+1j, 'str5', 'str6', 7, 8, 9, 10] # create list
b = a[0]                        # access one element
c = a[3:5]                      # access several elements
d = a[:5]                       # access several elements from begining
e = a[5:]                       # access several elements until end
f = a[:]                        # access all elements
g = a[:-2]                      # access several elements from begining
print a
print b
print c
print d
print e
print f
print g


[1, 2, 3.5, (4+1j), 'str5', 'str6', 7, 8, 9, 10]
1
[(4+1j), 'str5']
[1, 2, 3.5, (4+1j), 'str5']
['str6', 7, 8, 9, 10]
[1, 2, 3.5, (4+1j), 'str5', 'str6', 7, 8, 9, 10]
[1, 2, 3.5, (4+1j), 'str5', 'str6', 7, 8]

In [31]:
a = ''' 
 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1
'''

Operations with lists


In [6]:
a = range(10)
a = range(0, 10)
a = range(0, 10, 1)

a[9] = 11                  # replace one element
a[0:2] = ['0', '1']        # replace several elements
del a[8]                   # remove element
b = a[:4] + a[4:]          # concatenate two lists
c = [[1, 2, 3], [4, 5, 6]] # create nested list

c = [[1, 2, 3],            # nested list
     [4, 5, 6]]            # on multiple lines

d = [a[0:4], a[4:]]        # nested list from two sub-lists
e = [1, 2, 3] * 3          # replicate list
f = [[1, 2, 3]] * 3          # replicate list

print a
print b
print c
print d
print e
print f


['0', '1', 2, 3, 4, 5, 6, 7, 11]
['0', '1', 2, 3, 4, 5, 6, 7, 11]
[[1, 2, 3], [4, 5, 6]]
[['0', '1', 2, 3], [4, 5, 6, 7, 11]]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Tuples


In [7]:
a = (1,2,3)          # create tuple
b = 1,2,3            # create tuple
c, d, e = 1, 2, 3    # multiple assignment
f, g = c, d          # multiple assignment
f, g = g, f          # switch values
print a,b,c,d,e,f,g


(1, 2, 3) (1, 2, 3) 1 2 3 2 1

Dictionaries


In [8]:
a = {1: 123, 2.5: 'text', 'key3': [1,2,3]} # define dictionary

a = {    1 : 123,           # define dictionary 
       2.5 : 'text',        # on multiple lines
     'm': [1,2,3]}

b = a[1]                    # acces by key
c = a[2.5]                  # acces by key
d = a['m']               # acces by key
e = {}                      # create empty dict
e['new key'] = 'new value'  # add key:value to the dict
e[0] = 'new value'  # add key:value to the dict

print a
print b
print c
print d
print e
print e[0]


{2.5: 'text', 1: 123, 'm': [1, 2, 3]}
123
text
[1, 2, 3]
{0: 'new value', 'new key': 'new value'}
new value

Objects

Everything is object

  • Object is a container for data and functions
  • Data is called value (or attributes)
  • Functions are called methods

In [9]:
a = '   LoremIpsumDolorSitAmet   '
c = a.strip()

d = [0, 2, 1, 5, 4]
d.sort()
print a
print c
print d


   LoremIpsumDolorSitAmet   
LoremIpsumDolorSitAmet
[0, 1, 2, 4, 5]

Important methods of 'string'


In [10]:
# STRINGS
a = '   LaremIpsumDalarSitAmet   '
b = a.replace('a','o')
c = b.find('Lo')
d = '_'.join(['Larem', 'Ipsum', 'Dalar', 'Sit', 'Amet'])
                                  # a = '_'; a.join(...)
e = d.split('_')
f = a.replace('a', 'o').strip().split('m')


print a
print b
print c
print d
print e
print f


   LaremIpsumDalarSitAmet   
   LoremIpsumDolorSitAmet   
3
Larem_Ipsum_Dalar_Sit_Amet
['Larem', 'Ipsum', 'Dalar', 'Sit', 'Amet']
['Lore', 'Ipsu', 'DolorSitA', 'et']

Importnat methods of 'list'


In [11]:
a = [0, 1, 2, 3, 4, 5, 6, 7, 8]
a.append(9)
a.extend([10,11])
a.insert(2, 200)
b = a.pop(3)
a.remove(5)
a.sort()
a.reverse()
print a, b


[200, 11, 10, 9, 8, 7, 6, 4, 3, 1, 0] 2

Modules, packages and scripts


In [12]:
from IPython.display import Image 
Image('python_modules.png')


Out[12]:

In [13]:
import os                            # import entire package
a = os.path.exists('some_file.txt')

import os.path                       # import module
a = os.path.exists('some_file.txt')

from os import path                  # import module
a = path.exists('some_file.txt')

from os.path import *           # import function
a = exists('some_file.txt')

from os.path import exists as xsts   # import function with nickname
a = xsts('some_file.txt')

Control flow


In [14]:
if 2**2 == 4:
    print('Obvious!')


Obvious!

In [15]:
for i in [1,2,3,4,5]:
    print i


1
2
3
4
5

In [16]:
for i in range(10):
    if i % 2 == 0:
        j = 'Even number %d' % i
        print j


Even number 0
Even number 2
Even number 4
Even number 6
Even number 8

Functions


In [17]:
def square(a):
    b = a ** 2
    
    return b

print square(10)


100

Numerical Python (Numpy)


In [18]:
import numpy as np

In [19]:
# create array
a = np.array([1,2,3,4])

In [20]:
# fast!
L = range(100)
%timeit [i**2 for i in L]

a = np.arange(100)
%timeit a**2


100000 loops, best of 3: 5.31 µs per loop
The slowest run took 21.75 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 691 ns per loop

In [21]:
a = np.random.randn(5, 5)
print a


[[ 0.22825206  0.75222083  0.33492967 -1.38766385 -0.10466555]
 [-1.48902279  0.50789761  0.21393763  0.3995456   0.04325799]
 [-1.12616186 -0.84876954 -0.39058583 -2.2296693   0.69905278]
 [ 0.84116707  1.44859738 -0.72533201  0.97801494 -1.44170088]
 [-0.11288642  0.91013592 -1.0949002   1.75008238 -1.53711699]]

Basic visualisation


In [22]:
%matplotlib inline 
import matplotlib.pyplot as plt

In [23]:
plt.plot([1,2,3,4], 'o-')


Out[23]:
[<matplotlib.lines.Line2D at 0x7f5569e88390>]

In [24]:
plt.imshow(a, interpolation='nearest')
plt.colorbar()
plt.title('Random matrix')


Out[24]:
<matplotlib.text.Text at 0x7f5569d0a250>

Scientific Python (scipy)


In [25]:
from scipy import ndimage
from scipy import misc

In [26]:
lena = misc.lena()
plt.imshow(lena, cmap='gray')
plt.show()



In [27]:
noisy_lena = lena + lena.std() * np.random.standard_normal(lena.shape)
plt.imshow(noisy_lena, cmap='gray')


Out[27]:
<matplotlib.image.AxesImage at 0x7f5565f1cc10>

In [28]:
from scipy import signal
wiener_lena = signal.wiener(noisy_lena, (5,5))
plt.imshow(wiener_lena, cmap='gray')


Out[28]:
<matplotlib.image.AxesImage at 0x7f555c903d10>

In [29]:
from scipy.ndimage.filters import sobel

edge0 = sobel(wiener_lena, 0)
edge1 = sobel(wiener_lena, 1)
plt.imshow(np.hypot(edge0, edge1), vmax=500)
plt.colorbar()


Out[29]:
<matplotlib.colorbar.Colorbar instance at 0x7f555c7be758>

In [ ]: